package com.tjhzzx.ibmsSupervisor.login;

import com.tjhzzx.ibmsSupervisor.util.Constants;
import com.tridium.authn.BAuthenticationService;
import com.tridium.authn.BDigestAuthenticationScheme;
import com.tridium.web.CookieUtil;
import com.tridium.web.Template;
import org.owasp.encoder.Encode;

import javax.baja.authn.BAuthenticationScheme;
import javax.baja.io.HtmlWriter;
import javax.baja.naming.BOrd;
import javax.baja.nre.util.TextUtil;
import javax.baja.sys.*;
import javax.baja.user.BUserService;
import javax.baja.util.Lexicon;
import javax.baja.web.BClientEnvironments;
import javax.baja.web.BLoginTemplate;
import javax.baja.web.BWebService;
import javax.baja.web.authn.BILoginHTMLForm;
import javax.baja.web.mobile.BMobileClientEnvironment;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class BTlsLoginTemplate extends BLoginTemplate {

    private static final BOrd loginTemplate = BOrd.make("module://web/com/tridium/web/rc/loginN4.vm");
    private static final BOrd preLoginTemplate = BOrd.make("module://web/com/tridium/web/rc/preLoginFormN4.vm");
    private static final BOrd kerberosTemplate = BOrd.make("module://web/com/tridium/web/rc/kerberosN4.vm");
    public static final BTlsLoginTemplate INSTANCE = new BTlsLoginTemplate();

    @Override
    public void write(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = getRequestedUsername(request);
        HtmlWriter htmlwriter = new HtmlWriter(response.getWriter());
        String file = "login.html";
        if (username != null) {
            file = "loginP.html";
        }
        FileReader fr = new FileReader(Sys.getStationHome() + "/html/login/" + file);
        BufferedReader br = new BufferedReader(fr);
        while (br.ready()) {
            String temp = br.readLine();
            if (temp.indexOf("[nameTag]") != -1) {
                temp = TextUtil.replace(temp, "[nameTag]", username);
//                temp = temp.replace("[nameTag]", username);
            }
            htmlwriter.println(temp);
        }
        br.close();
        fr.close();
    }

    @Override
    public BOrd resourceToOrd(String path) {
        if (path.indexOf("custom") != -1) {
            path = path.substring("custom/".length(), path.length());
            String modulePath = Constants.STATION_NAME;
            BOrd ord = BOrd.make("module://" + modulePath + "/rc" + path);
            return ord;
        }
        return BOrd.make("module://web/com/tridium/web/rc" + path);
    }

    private String getRequestedUsername(HttpServletRequest request) {
        String userCookieName = "niagara_userid";
        Cookie cookie = CookieUtil.getCookieFromName(request, userCookieName);
        if (cookie != null) {
            return cookie.getValue();
        }
        return null;
    }

    private String getInnerForm(String username, Context context, HttpServletRequest request)
            throws IOException {
        if (username != null) {
            BUserService userService = (BUserService) Sys.getService(BUserService.TYPE);
            BAuthenticationScheme authnScheme = null;
            BILoginHTMLForm innerFormBuilder = null;
            HttpSession session = request.getSession(true);
            innerFormBuilder = (BILoginHTMLForm) session.getAttribute("currentForm");
            try {
                authnScheme = userService.getAuthenticationSchemeForUser(username);
            } catch (Exception e) {
                authnScheme = new BDigestAuthenticationScheme();
            }
            if (innerFormBuilder == null) {
                innerFormBuilder = authnScheme.getAgentOn(BILoginHTMLForm.class);
                if (innerFormBuilder == null) {
                    authnScheme = new BDigestAuthenticationScheme();
                    innerFormBuilder = authnScheme.getAgentOn(BILoginHTMLForm.class);
                }
                session.setAttribute("currentForm", innerFormBuilder);
            }
            context = new BasicContext(context, BFacets.make("initUsername", Encode.forHtmlAttribute(username)));
            String html = innerFormBuilder.getLoginFormHTML(context, false);
            return html;
        }
        Lexicon lex = Lexicon.make("web", context.getLanguage());
        Map<String, String> innerMap = new HashMap();
        innerMap.put("userName", lex.get("login.username"));
        innerMap.put("login", lex.get("login"));
        String template = Template.process(innerMap, preLoginTemplate);
        BAuthenticationService authnService = (BAuthenticationService) Sys.getService(BAuthenticationService.TYPE);
        boolean kerb = false;
        for (BAuthenticationScheme scheme : authnService.getSupportedSchemes()) {
            if (scheme.getSchemeName().equals("n4Kerberos")) {
                kerb = true;
                break;
            }
        }
        if (kerb) {
            Object kerbMap = new HashMap();
            String hideCookieName = "niagara_hide_kerb_login";
            Cookie cookie = CookieUtil.getCookieFromName(request, hideCookieName);
            if ((cookie != null) && (cookie.getValue().equals("true"))) {
                ((Map) kerbMap).put("hideOrShowText", lex.get("ldap.kerberos.web.showLogin"));
                ((Map) kerbMap).put("hide", "display:none;");
            } else {
                ((Map) kerbMap).put("hideOrShowText", lex.get("ldap.kerberos.web.hideLogin"));
                ((Map) kerbMap).put("hide", "");
            }
            ((Map) kerbMap).put("descriptionText", lex.get("ldap.kerberos.web.description"));
            ((Map) kerbMap).put("helpText", lex.get("ldap.kerberos.web.help"));
            ((Map) kerbMap).put("buttonText", lex.get("ldap.kerberos.web.loginButton"));
            ((Map) kerbMap).put("rememberText", lex.get("ldap.kerberos.web.remember"));
            ((Map) kerbMap).put("hideText", lex.get("ldap.kerberos.web.hideLogin"));
            ((Map) kerbMap).put("showText", lex.get("ldap.kerberos.web.showLogin"));
            template = template + Template.process((Map) kerbMap, kerberosTemplate);
        }
        return template;
    }

    private boolean isMobileEnvironment(String ua, BWebService service) {
        BClientEnvironments envs = service.getClientEnvironments();
        if (envs != null) {
            SlotCursor cursor = envs.getProperties();
            if (cursor.next(BMobileClientEnvironment.class)) {
                BMobileClientEnvironment env = (BMobileClientEnvironment) cursor.get();
                if (env.matchesUserAgentPattern(ua)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static final Type TYPE = Sys.loadType(BTlsLoginTemplate.class);
    public Type getType() {
        return TYPE;
    }
}
